package com.showsu.editor.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author: William
 * @Description:
 * @Date: Created in 5:11 下午 2023/3/21
 * @Modified By:
 */
@Slf4j
public class MD5Utils {

    public static void main(String[] args) {
        System.out.println(getMD5("showsuhaha"));
    }

    public static String getMD5(String pwd) {
        if (StringUtils.isBlank(pwd)) {
            return null;
        }
        String r_pw = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(pwd.getBytes());
            byte[] b = md.digest();
            StringBuffer buf = new StringBuffer("");
            for(int offset = 0; offset < b.length; ++offset) {
                int i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            r_pw = buf.toString();
        } catch (NoSuchAlgorithmException var7) {
            var7.printStackTrace();
        }
        if (r_pw != null && r_pw.length() == 32) {
            return r_pw;
        } else {
            log.error("密码加密出错pwd:{}", pwd);
            throw new IllegalArgumentException("请输入有效的密码格式！");
        }
    }
}
